package com.sse.serviceSsePush.controller;

import com.wyc.internalCommon.util.SsePrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class SseController {

    public static Map<String,SseEmitter> sseEmitterMap = new HashMap<>();

    /**
     * 司机/用户 与客户端建立连接
     * @param userId
     * @param identity
     * @return
     */
    @RequestMapping("/concent")
    public SseEmitter connect(@RequestParam("userId") String userId,@RequestParam("identity") String identity){
        log.info("建立连接成功，用户id："+userId+",身份标识："+identity);
        // 跟页面建立连接
        SseEmitter sse = new SseEmitter(0L);
        String sseKey = SsePrefixUtils.generatorSseKey(userId, identity);
        sseEmitterMap.put(sseKey,sse);
        return sse;
    }

    /**
     * 发送消息
     * @param userId 消息接收者
     * @param identity 接收者身份标识
     * @param content 消息内容
     * @return
     */
    @RequestMapping("/push")
    public String push(@RequestParam("userId") String userId,@RequestParam("identity") String identity,@RequestParam("content") String content){
        String sseKey = SsePrefixUtils.generatorSseKey(userId, identity);
        try {
            if (sseEmitterMap.containsKey(sseKey)){
                sseEmitterMap.get(sseKey).send(content);
            }
        } catch (IOException e) {
            return "推送失败";
        }
        return "给用户："+sseKey+"，发送了消息"+content;
    }

    /**
     * 关闭连接
     * @param userId
     * @param identity 接收者身份标识
     * @return
     */
    @RequestMapping("/sourceClose")
    public String close(@RequestParam("userId") String userId,@RequestParam("identity") String identity){
        String sseKey = SsePrefixUtils.generatorSseKey(userId, identity);
        log.info("关闭连接："+sseKey);
        if (sseEmitterMap.containsKey(sseKey)){
            sseEmitterMap.remove(userId);
        }
        return "close success";
    }

}
